package com.dy.lock.screen.component.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.pojo.CustomerTagRelation;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.CustomerTagService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.vo.CustomerTagVo;
import com.google.gson.Gson;
@Component("customerTagComponent")
public class CustomerTagComponentImpl implements
		com.dy.lock.screen.component.CustomerTagComponent {
	private static final Logger log = Logger.getLogger(CustomerTagComponentImpl.class);
	private Gson gson;
	@Resource(name = "customerTagService")
	private CustomerTagService customerTagService;
	
	public CustomerTagComponentImpl() {
		gson = CommonUtil.gson();
	}
	
	@Override
	public CustomerTagVo getCustomerTags(String body, Head head) {
		CustomerTagVo vo = gson.fromJson(body, CustomerTagVo.class);
		if (vo != null && StringUtils.isNotBlank(vo.getUserId())) {
			List<CustomerTagRelation> tagRelations =  this.customerTagService.getCustomerTags(vo.getUserId());
			List<String> tags = new ArrayList<String>();
 			for (CustomerTagRelation customerTagRelation : tagRelations) {
 				tags.add(customerTagRelation.getAdTagId());
			}
 			vo.setTags(tags);
			return vo;
		}
		else {
			log.info("requestId:" + head.getRequestId() + ",获取广告偏好时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public CustomerTagVo updateCustomerTags(String body, Head head) {
		CustomerTagVo vo = gson.fromJson(body, CustomerTagVo.class);
		if (vo != null && StringUtils.isNotBlank(vo.getUserId()) && vo.getTags().size() > 0) {
			Boolean result =  this.customerTagService.updateCustomerTags(vo.getUserId(), vo.getTags());
 			vo.setResult(result);
			return vo;
		}
		else {
			log.info("requestId:" + head.getRequestId() + ",修改广告偏好时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

}
